package cn.rokhdelar.umbrsapi.management.service;

import cn.rokhdelar.umbrsapi.management.entity.LoginDTO;
import cn.rokhdelar.umbrsapi.management.entity.SysUser;
import io.micrometer.common.util.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class AuthenticationService {
    private final AuthenticationManager authenticationManager;
    private final CaptchaService captchaService;
    private final JwtService jwtService;

    public AuthenticationService(AuthenticationManager authenticationManager,
                                 CaptchaService captchaService, JwtService jwtService) {
        this.authenticationManager = authenticationManager;
        this.captchaService = captchaService;
        this.jwtService = jwtService;
    }

    /**
     * 登录服务
     * @param loginDTO
     * @return
     */
    public Map<String, Object> login(LoginDTO loginDTO) {
        if(StringUtils.isEmpty(loginDTO.getUsername()) || StringUtils.isEmpty(loginDTO.getPassword())) {
            throw new UsernameNotFoundException("无效的用户名和密码。");
        }

//        Map<String, Object> re = captchaService.verifyCaptcha(loginDTO.getCaptchaUUID(), loginDTO.getCaptchaCode());
//        if (((Boolean)re.get("code")) != Boolean.TRUE) {
//            return re;
//        }

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
        );

        if(Objects.isNull(authentication)) {
            throw new RuntimeException("登录失败。");
        }
        SysUser user = (SysUser)authentication.getPrincipal();
        user.setPassword(null);
        HashMap<String, Object> map = jwtService.generateToken(user);
        map.put("user", user);
        return map;
    }
}
